package org.lq.util;

import lombok.extern.log4j.Log4j;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author 无语
 * @create 2020-10-06 18:31
 */
@Log4j
public class FtpUtils {

    public static final String HOST;
    public static final String PORT;
    public static final String USERNAME;
    public static final String PASSWORD;

    static {
        HOST = PropertiesUtils.getKey(CommonConstant.FTP_HOST);
        PORT=PropertiesUtils.getKey(CommonConstant.FTP_PORT);
        USERNAME=PropertiesUtils.getKey(CommonConstant.FTP_USERNAME);
        PASSWORD=PropertiesUtils.getKey(CommonConstant.FTP_PASSWORD);

        log.info("FTP.HOST="+HOST);
        log.info("FTP.PORT="+PORT);
        log.info("FTP.USERNAME="+USERNAME);
        log.info("FTP.PASSWORD="+PASSWORD);

    }

    /**
     * 文件上传
     * @param filename 上传的文件名称
     * @param is 上传的文件流
     * @return
     */
    public static boolean uploadFile(String filename,String filePath ,InputStream is){
        boolean result = false;
        FTPClient ftpClient = new FTPClient();
        try {
            //连接FTP服务器
            ftpClient.connect(HOST,Integer.parseInt(PORT));
            //登录
            boolean login = ftpClient.login(USERNAME, PASSWORD);
            log.info("FTP登录："+login);
            //切换到上传目录中
            if ( !ftpClient.changeWorkingDirectory(filePath) ){
                ftpClient.makeDirectory(filePath);
                ftpClient.changeWorkingDirectory(filePath);
                log.info("文件上传路径:"+filePath);
            }
            //设置为被动模式
            ftpClient.enterLocalPassiveMode();
            //设置上传文件的类型为二进制类型
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            if (!ftpClient.storeFile(filename,is)){
                log.info("文件上传结果："+result);
                return result;
            }
            is.close();
            ftpClient.logout();
            result = true;
            log.info("文件上传结果："+result);
        } catch (IOException e) {
            log.error("FTP文件上传失败",e);
        }finally {
            if (ftpClient.isConnected()){
                try {
                    ftpClient.disconnect();
                    log.info("FTP文件上传完毕!");
                } catch (IOException e) {
                    log.error("FTP服务器断开失败",e);
                }
            }
        }
        return result;
    }


}
